package com.quick.proxy.core.handler;

import cn.hutool.json.JSONUtil;
import com.quick.proxy.core.ChannelAttribute;
import com.quick.proxy.core.ProxyMessage;
import com.quick.proxy.core.utils.ProtocolUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Optional;


/**
 * Description: 发送数据时编码
 * Author: 吃素不吃肉
 * Date: 2023/7/4
 *
 * @author 吃素不吃肉
 */
@Sharable
@Component
@Slf4j
public class ProtocolEncoder extends MessageToByteEncoder<Object> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object object, ByteBuf byteBuf) {
        byte[] sendCommand = ((byte[]) object);
        ProxyMessage proxyMessage = ProtocolUtils.getProxyMessage(sendCommand);
        String accessKey = Optional.ofNullable(channelHandlerContext.channel().attr(ChannelAttribute.ACCESS_KEY_PROXY_CHANNEL).get()).orElse("auth");
        log.debug("[{}][{}]->{}", accessKey, proxyMessage.getCmdType(), JSONUtil.toJsonStr(proxyMessage));
        byteBuf.writeBytes(sendCommand, 0, sendCommand.length);
    }
}
